<template>
  <div class="box-content">
    <div class="navigation">设备列表</div>
    <!--搜索-->
    <div class="mt-3">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-input type="text" size="small" style="margin-right: 10px;width: 220px;" v-model="search.inputName" :clearable="true" placeholder="输入关键字(设备名称或设备编号)"></el-input>
          <el-cascader
                  size="small"
                  style="margin-right: 10px;width: 240px;"
                  placeholder="选择一级景区或者二级景点"
                  :options="treeData"
                  @change="handleChangeTree"
                  filterable
                  :clearable="true"
                  change-on-select
          ></el-cascader>
          <el-button type="primary" size="small" @click="onSearch">查询</el-button>
          <el-button type="primary" size="small" @click="createAccount">新增</el-button>
        </el-col>
      </el-row>
    </div>
    <!--表格-->
    <div class="mt-3">
      <el-table
              :data="userData"
              v-loading="loading"
              align="center"
              :element-loading-text="loadText"
              :header-cell-style="tableHeaderColor"
              stripe
              style="width: 100%">
        <el-table-column
                prop="id"
                align="center"
                label="编号"
                width="100"
        >
        </el-table-column>
        <el-table-column
                prop="ta_name"
                align="center"
                width="100"
                label="景点"
        >
        </el-table-column>
        <el-table-column
                prop="dvc_name"
                align="center"
                width="80"
                label="设备分类"
        >
        </el-table-column>
        <el-table-column
                prop="dv_name"
                align="center"
                width="100"
                label="设备名"
        >
        </el-table-column>
        <el-table-column
                prop="sn"
                align="center"
                width="100"
                label="设备编号"
        >
        </el-table-column>
        <el-table-column
                prop="longitude"
                align="center"
                width="120"
                label="经度"
        >
        </el-table-column>
        <el-table-column
                prop="latitude"
                align="center"
                width="120"
                label="纬度"
        >
        </el-table-column>

        <el-table-column
                prop="address"
                align="center"
                width="200"
                label="放置地址"
        >
        </el-table-column>
        <el-table-column
                prop="status"
                align="center"
                label="状态"
        >
          <template slot-scope="scope">
            <el-switch
                    v-model="scope.row.status"
                    :active-value="1"
                    :inactive-value="2"
                    @change=changeStatus(scope.row)></el-switch>
          </template>

        </el-table-column>
        <el-table-column
                label="创建时间"
                align="center"
                width="100">
          <template slot-scope="scope">
            <div align="center">{{scope.row['created_at']?scope.row['created_at'].slice(0, 11):'无'}}</div>
            <div align="center">{{scope.row['created_at']?scope.row['created_at'].slice(11 ):'无'}}</div>
          </template>
        </el-table-column>
        <el-table-column
                label="操作"
                align="center"
                fixed="right"
                width="160">
          <template slot-scope="scope">
            <el-button
                    size="small"
                    type="primary"
                    @click="handleEdit(scope.row)">编辑
            </el-button>
            <el-button
                    size="small"
                    type="danger"
                    @click="handleDelete(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="mt-3 float-right">
        <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageInfo.current_page"
                :page-size="pageInfo.per_page"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageInfo.total">
        </el-pagination>
      </div>
    </div>
    <!--新增对话框-->
    <el-dialog :title="dialog.title"
               :visible.sync="dialogFormVisible"
               :close-on-click-modal="false"
               width="600px">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px" v-loading="loadingDialig">
        <el-form-item label="设备分类ID" prop="dvc_ids">
          <!--<el-select v-model="form.dvc_id" placeholder="请选择设备分类ID"  :clearable="true" style="width: 450px;">-->
            <!--<el-option-->
                    <!--v-for="item in dvcData"-->
                    <!--:key="item.id"-->
                    <!--:label="item.dvc_name"-->
                    <!--:value="item.id">-->
            <!--</el-option>-->
          <!--</el-select>-->
          <el-cascader
                  v-model="form.dvc_ids"
                  style="width: 450px;"
                  placeholder="设备分类ID"
                  :options="dvcData"
                  @change="handleChangeTreeFenLei"
                  filterable
                  change-on-select
          ></el-cascader>
          <!--<el-input v-model="form.dvc_id" placeholder="请输入设备分类ID" style="width: 450px;"></el-input>-->
        </el-form-item>
        <el-form-item label="设备名" prop="dv_name">
          <el-input v-model="form.dv_name" placeholder="请输入设备名" style="width: 450px;"></el-input>
        </el-form-item>
        <el-form-item label="设备编号" prop="sn">
          <el-input v-model="form.sn" placeholder="请输入设备编号" style="width: 450px;"></el-input>
        </el-form-item>
          <el-form-item label="设备经度" prop="longitude">
              <el-input type="number" v-model="form.longitude" placeholder="请输入设备经度" :clearable="true" style="width: 450px;"></el-input>
          </el-form-item>
          <el-form-item label="设备纬度" prop="latitude">
              <el-input type="number" v-model="form.latitude" placeholder="请输入设备纬度" :clearable="true" style="width: 450px;"></el-input>
            <el-button type="primary" :loading="loadingTransferStart" @click="transfer" style="margin-left: 10px">转换</el-button>
          </el-form-item>
          <el-form-item label="设备放置地址" prop="address">
              <el-input type="text" v-model="form.address" placeholder="请输入设备放置地址" :clearable="true" style="width: 450px;"></el-input>
          </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" v-if="!dialog.isEdit" :disabled="loadingTransfer" :loading="loadingCreate"
                   @click="submitCostomer('form')">{{loadingCreate?'创建中':'点击创建'}}
        </el-button>
        <el-button type="primary" v-if="dialog.isEdit" :disabled="loadingTransfer" :loading="loadingCreate" @click="submitCostomer('form')">
          {{loadingCreate?'修改中':'点击修改'}}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
    export default {
        name: "accountList",
        data() {
            return {
                loadingTransfer:false,
                loadingTransferStart:false,
                baseId: null,
                pageInfo: {
                    per_page: 10,
                    total: 0,
                    current_page: 1
                },
                loadText: '数据加载中',
                userData: [],  // 设备列表
                dvcData: [], // 设备分类数据
                searchStr: '',
                search: {
                    inputName: '',
                    treeId:[]
                },
                loading: false,
                loadingDialig: false,
                loadingCreate: false,
                dialogFormVisible: false,
                form: {
                    dvc_ids:[],
                    dvc_id: '',
                    dv_name: '',
                    sn: '',
                    longitude: '',
                    latitude: '',
                    address: '',
                },
                treeData:[],

                dialog: {
                    title: '',
                    isEdit: false
                },
                rules: {
                    dvc_ids: [
                        {required: 'true', message: '请选择设备分类ID', trigger: 'change'}
                    ],
                    dv_name: [
                        {required: 'true', message: '请输入设备名', trigger: 'change'}
                    ],
                    sn: [
                        {required: 'true', message: '请输入设备编号', trigger: 'change'}
                    ],
                }
            }
        },
        watch: {
            dialogFormVisible: function (val) {
                if (!val) {
                    Object.keys(this.form).forEach(key => this.form[key] = '');
                    this.$refs['form'].resetFields();
                    this.form.dvc_ids = [];
                }
            }
        },
        created() {
            this.getFenLeiList();
            this.getTreeList();
            this.getAccountList();
        },
        methods: {
            transfer() {
                if (!this.form.longitude || !this.form.latitude) {
                    this.$message.warning('经纬度必填！否则无法转换');
                    return false;
                }
                let params = {
                    longitude: this.form.longitude,
                    latitude: this.form.latitude
                };
                this.loadingTransfer = true;
                this.loadingTransferStart = true;
                this.$http.post('api/auth/getCoords', params)
                    .then((result) => {
                        if (result.status_code == 200) {
                            this.$message({
                                type: 'success',
                                message: '转换成功',
                                during: 1000
                            });
                            this.form.longitude = result.data.x;
                            this.form.latitude = result.data.y;
                        } else {
                            this.$message.warning(result.msg);
                        }
                        this.loadingTransfer = false;
                        this.loadingTransferStart = false;
                    })
                    .catch((err) => {
                        this.loadingTransfer = false;
                        this.loadingTransferStart = false;
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            handleChangeTree(val) {
                this.search.treeId = val;
            },
            handleChangeTreeFenLei(val) {
                if (val) {
                    if (val.length == 1) {
                        this.form.dvc_id = val[0]
                    } else if (val.length == 2) {
                        this.form.dvc_id = val[1]
                    } else if (val.length == 3) {
                        this.form.dvc_id = val[2]
                    }
                }
                console.info(this.form.dvc_id)
            },
            changeName(val) {
                this.search.inputName = val;
            },
            createAccount() {
                this.dialog.title = '添加设备';
                this.dialog.isEdit = false;
                this.dialogFormVisible = true;
            },
            changeStatus(val) {
                let params = {
                    dvc_id: val.dvc_id,
                    status: val.status
                };
                this.$http.put('api/auth/device/' + val.id, params)
                    .then((result) => {
                        if (result.status_code == 200) {
                            this.$message({
                                type: 'success',
                                message: result.msg,
                                during: 1000
                            });
                        } else {
                            this.$message.warning(result.msg);
                        }
                    })
                    .catch((err) => {
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            getFenLeiList() {
                this.$http.get('api/auth/deviceCategory?@action=cateTree')
                    .then((result) => {
                        if (result.status_code == 200) {
                            this.dvcData = result.data;
                        } else {
                            this.$message.warning(result.msg);
                        }
                    })
                    .catch((err) => {
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            getTreeList() {
                this.$http.get('api/auth/tree')
                    .then((result) => {
                        if (result.status_code == 200) {
                            this.treeData = result.data;
                        } else {
                            this.$message.warning(result.msg);
                        }
                    })
                    .catch((err) => {
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            getAccountList() {
                this.loading = true;
                this.$http.get('api/auth/device' + this.searchStr, {
                    params: {
                        pageSize: this.pageInfo.per_page,
                        page: this.pageInfo.current_page
                    }
                })
                    .then((result) => {
                        if (result.status_code == 200) {
                            this.userData = result.data.data;
                            this.pageInfo.total = result.data.total;
                        } else {
                            this.$message.warning(result.msg);
                        }
                        this.loading = false;
                    })
                    .catch((err) => {
                        this.loading = false;
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            onSearch() {
                this.searchStr = "";
                if (this.search.inputName) {
                    this.addConStr();
                    this.searchStr += `keyword=${this.search.inputName}`;
                }
                if (this.search.treeId && this.search.treeId.length > 0) {
                    this.addConStr();
                    if (this.search.treeId.length == 1) {
                        this.searchStr += `tr_id=${this.search.treeId[0]}`;
                    } else if (this.search.treeId.length == 2) {
                        this.searchStr += `ta_id=${this.search.treeId[1]}`;
                    }

                }
                this.pageInfo.current_page = 1;
                this.getAccountList();
            },
            addConStr() {
                if (this.searchStr.length > 0) {
                    this.searchStr += '&';
                } else {
                    this.searchStr += '?';
                }
            },
            submitCostomer(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.creatShanHu();
                    } else {
                        return false;
                    }
                });
            },
            creatShanHu() {
                this.loadingCreate = true;
                let params;
                if (this.dialog.isEdit) {
                    params={
                        dvc_id:this.form.dvc_id,
                        dv_name:this.form.dv_name,
                        sn:this.form.sn,
                        address:this.form.address,
                        longitude:this.form.longitude,
                        latitude:this.form.latitude,
                    };
                    this.$http.put('api/auth/device/' + this.baseId, params)
                        .then((result) => {
                            if (result.status_code == 200) {
                                this.$message({
                                    type: 'success',
                                    message: result.msg,
                                    during: 1000
                                });
                                this.getAccountList();
                                this.dialogFormVisible = false;
                            } else {
                                this.$message.warning(result.msg);
                            }
                            this.loadingCreate = false;
                        })
                        .catch((err) => {
                            this.loadingCreate = false;
                            this.$message.warning(err.data.msg || "数据异常，请重试");
                        })
                } else {
                    params={
                        dvc_id:this.form.dvc_id,
                        dv_name:this.form.dv_name,
                        sn:this.form.sn,
                        address:this.form.address,
                        longitude:this.form.longitude,
                        latitude:this.form.latitude,
                    };
                    this.$http.post('api/auth/device', params)
                        .then((result) => {
                            if (result.status_code == 200) {
                                this.$message({
                                    type: 'success',
                                    message: result.msg,
                                    during: 1000
                                });
                                this.getAccountList();
                                this.dialogFormVisible = false;
                            } else {
                                this.$message.warning(result.msg);
                            }
                            this.loadingCreate = false;

                        })
                        .catch((err) => {
                            this.loadingCreate = false;
                            this.$message.warning(err.data.msg || "数据异常，请重试");
                        })
                }

            },
            handleEdit(val) {
                this.baseId = val.id;
                this.dialog.title = '编辑设备';
                this.dialog.isEdit = true;
                this.dialogFormVisible = true;
                this.loadingDialig = true;
                this.$http.get('api/auth/device/' + val.id)
                    .then((result) => {
                        this.form.dvc_ids = [];
                        if (result.status_code == 200) {
                            this.dvcData.forEach(item1=>{
                                if (item1.value == result.data.dvc_id) {
                                    this.form.dvc_ids.push(result.data.dvc_id);
                                } else {
                                    if (item1.children && item1.children.length>0) {
                                        item1.children.forEach(item2=>{
                                            if (item2.value == result.data.dvc_id) {
                                                this.form.dvc_ids.push(item1.value);
                                                this.form.dvc_ids.push(item2.value);
                                            } else {
                                                if (item2.children && item2.children.length>0) {
                                                    item2.children.forEach(item3=>{
                                                        if (item3.value == result.data.dvc_id) {
                                                            this.form.dvc_ids.push(item1.value);
                                                            this.form.dvc_ids.push(item2.value);
                                                            this.form.dvc_ids.push(item3.value);
                                                        }
                                                    })
                                                }
                                            }
                                        })
                                    }
                                }
                            });
                            this.form.dvc_id = result.data.dvc_id;
                            this.form.dv_name = result.data.dv_name;
                            this.form.sn = result.data.sn;
                            this.form.address = result.data.address;
                            this.form.longitude = result.data.longitude;
                            this.form.latitude = result.data.latitude;


                        } else {
                            this.$message.warning(result.msg);
                        }
                        this.loadingDialig = false;
                        this.loadingCreate = false;
                    })
                    .catch((err) => {
                        this.loadingDialig = false;
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            handleDelete(val) {
                this.$confirm('此操作将删除此设备, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$http.delete('api/auth/device/' + val.id)
                        .then((result) => {
                            if (result.status_code == 200) {
                                this.$message({
                                    type: 'success',
                                    message: result.msg,
                                    during: 1000
                                });
                                this.getAccountList();
                            } else {
                                this.$message.warning(result.msg);
                            }
                        })
                        .catch((err) => {
                            this.$message.warning(err.data.msg || "数据异常，请重试");
                        })
                }).catch(() => {
                });
            },
            handleSizeChange(val) {
                this.pageInfo.current_page = 1;
                this.pageInfo.per_page = val;
                this.getAccountList();
            },
            handleCurrentChange(val) {
                this.pageInfo.current_page = val;
                this.getAccountList();
            },
            tableHeaderColor({row, column, rowIndex, columnIndex}) {
                if (rowIndex === 0) {
                    return 'background-color: #FAFAFA;color: #000;font-weight: 500;height:54px;font-size:14px'
                }
            },
        }
    }
</script>

<style lang="less" scoped>
</style>